package com.dek.ssm.ch2.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.junit.Test;

public class InterceptorJdkProxy implements InvocationHandler {
	
	private Object target; // 真实对象
	private String interceptorClazz = null; //拦截器全限定名

	public InterceptorJdkProxy(Object target, String interceptorClazz) {
		super();
		this.target = target;
		this.interceptorClazz = interceptorClazz;
	}
	
	/**
	 *  绑定委托对象
	 * @param target
	 * @param interceptorClazz
	 * @return
	 */
	public static Object bind(Object target, String interceptorClazz) {
		return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), 
					new InterceptorJdkProxy(target, interceptorClazz));
	}
	
	/**
	 * 通过代理对象调用方法
	 */
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if (interceptorClazz == null) {
			return method.invoke(target, args);
		}
		Object result = null;
		Interceptor interceptor = (Interceptor) Class.forName(interceptorClazz).newInstance();
		if (interceptor.before(proxy, args, method, args)) {
			result = method.invoke(target, args);
		} else {
			interceptor.around(proxy, args, method, args);
		}
		//调用后置方法
		interceptor.after(proxy, args, method, args);
		return result;
	}
	
	
	public static void main(String[] args) {
		HelloWorld proxy = (HelloWorld) InterceptorJdkProxy.bind(new HelloWorldImpl(), "com.dek.ssm.ch2.proxy.MyInterceptor");
		proxy.sayHelloWorld();
	}
	
}
